# -*-coding:utf-8 -*-
import base64
import datetime
import os
import pathlib
import time

from .base import XZBaseHandler


class ImageHandler(XZBaseHandler):

    def add_warn(self, msg):
        # dict_keys(['imageStr', 'warningTime', 'vehicleId', 'warningPlace', 'gpsLat', 'gpsLon', 'warningId'])
        vehicle_id = self.map2new_vehicle_id(msg['vehicleId'])
        if not vehicle_id:  # 找不到vehicle_id
            return
        for warning_id in msg['warningId'].split(','):
            category = self.WARNING_TYPE_MAP[warning_id]
            if category:
                category = self.WARNING_TYPE_MAP[msg['warningId']]
                data = {
                    "category": self.WARNING_TYPE_MAP[msg['warningId']],
                    "start_time": msg['warningTime'],
                    "end_time": msg['warningTime'],
                    'vehicle_id': vehicle_id,
                    'vehicle': vehicle_id,
                    'media_uri_category': 1,
                    "media_uri": self.save(msg['imageStr']),
                    "location": {
                        "latitude": msg['gpsLat'],
                        "longitude": msg['gpsLon'],
                        "gps_time": msg['warningTime']
                    }
                }
                self.yb_api.send_alarm(data)

    def contrast_warn_image(self, msg):
        # 换人报警
        # dict_keys(['BaseImage', 'vehicleId', 'warningPlace'])
        pass

    def save(self, base64_image):
        filename = int(time.time() * 100)
        day = datetime.date.today().strftime('%Y%m%d')
        p = os.path.join(self.MEDIA_UPLOADS_PATH, f'{day}/images/')
        pathlib.Path(p).mkdir(parents=True, exist_ok=True)
        with open(os.path.join(p, f'{filename}.png'), 'wb') as fh:
            fh.write(base64.b64decode(base64_image))
        return f'uploads/{day}/images/{filename}.png'
